import os
from time import time

from flask import current_app
from flask import redirect, jsonify
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from os import path

from werkzeug.utils import secure_filename

from cyds import db
from cyds.models import User, Squad, News, Category, Applicant
from . import admin_blu


@admin_blu.route('/apply', methods=["POST", "GET"])
def get_apply():
    """查询报名的小组分类显示"""
    if request.method == 'GET':
        return render_template("admin/html/group.html")

    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')
    category_id = request.args.get('category_id', "2")

    try:
        page = int(page)
        per_page = int(per_page)
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=404, errmsg="参数错误")

    try:
        applicant = Applicant.query.filter_by(school=category_id).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=404, errmsg="数据查询错误")

    squad_model_list = applicant.items
    total_page = applicant.pages
    current_page = applicant.page

    group_dict_li = []
    for squad in squad_model_list:
        squad_dict = {
            "name": squad.name,
            "school": squad.school,
            "profession": squad.profession,
            "grade": squad.grade
        }
        group_dict_li.append(squad_dict)

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "group_dict_li": group_dict_li
    }

    return jsonify(errno=200, errmsg="OK", data=data)


@admin_blu.route('/video', methods=['POST', 'GET'])
def upload_video():

    if request.method == 'GET':
        return render_template("admin/html/up_squad.html")

    name = request.form.get('name')
    category = request.form.get('school')
    profession = request.form.get('profession')
    grade = request.form.get('grade')
    video = request.files.get('video')

    if not all([name, category, video, profession, grade]):
        return jsonify(errno=404, errmsg="参数错误")

    # 上传视频
    vid = secure_filename(video.filename)
    ti = time()
    video_name = str(ti)+vid
    try:
        base_path = path.dirname(path.dirname(path.dirname(path.abspath(__file__))))
        upload_path = path.join(base_path, "static", 'photo_video', 'video', secure_filename(video.filename))
        # file_name = upload_path + secure_filename(video.filename)
        video.save(upload_path)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=500, errmsg="上传失败")

    school = Category.query.filter_by(name=category).first()
    # print(type(school))
    if not school:
        cat = Category()
        cat.name = category
        try:
            db.session.add(cat)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
        school = Category.query.filter_by(name=category).first()

    squad = Squad()
    squad.name = name
    squad.school = school.id
    squad.profession = profession
    squad.grade = grade
    squad.video_url = video_name

    try:
        db.session.add(squad)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=500, errmsg="保存到数据库失败")

    return jsonify(errno=200, errmsg="OK")


@admin_blu.route('/new', methods=["POST", "GET"])
def upload_new():

    if request.method == "GET":
        return render_template("admin/html/up_news.html")

    title = request.form.get('title')
    content = request.form.get('content')
    image = request.files['image']

    img = secure_filename(image.filename)
    ti = time()
    image_name = str(ti) + img

    if not all([title, content, image]):
        return jsonify(errno=404, errmsg="参数错误")

    try:

        po = path.dirname(path.dirname(path.dirname(path.abspath(__file__))))

        upload_path = path.join(po, 'static', "photo_video", "image", image_name)
        print(upload_path)
        # file_name = upload_path + secure_filename(image.filename)
        image.save(upload_path)

    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=501, errmsg="上传失败")

    news = News()
    news.title = title
    news.content = content
    news.image_url = image_name

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=500, errmsg="保存失败")

    return jsonify(errno=200, errmsg="OK")


@admin_blu.route("/login", methods=['GET', 'POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')

    print(username, password)

    if not all([username, password]):
        return render_template('admin/html/login.html', errmsg='参数不全')

    try:
        username = str(username)
        password = str(password)
        user = User.query.filter_by(username=username).first()
        print(user.password)

    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/html/login.html', errmsg="用户信息查询失败")

    if not user:
        return render_template('admin/html/login.html', errmsg="用户不存在")

    if user.password != password:
        return render_template('admin/html/login.html', errmsg="用户密码错误")

    session["user_id"] = user.id

    # 跳转到后面管理首页
    return redirect(url_for('admin.index'))


@admin_blu.route('/index')
def index():

    return render_template("admin/html/index.html")


